﻿using Magicodes.Logger;
using Magicodes.Logger.NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;


namespace TXH.DataSync.Helper
{
    public class ApiHelper
    {
        public static LoggerBase Logger = new NLogLogger("ApiHelper");
        public static bool Post(string api, string data)
        {
            var apiUrl = string.Format("{0}/{1}", ConfigHelper.ConfigInfo.RemoteApiUrl, api);
            using (var client = new HttpClient())
            {
                HttpResponseMessage result = null;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Access-Token", "248d924998a34a75bad3f2194895ce97");
                var httpContent = new StringContent(data) { };
                httpContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
                result = client.PostAsync(apiUrl, httpContent).Result;
                if (result.StatusCode == HttpStatusCode.OK)
                {
                    var str = result.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(str);
                    Logger.Log(LoggerLevels.Debug, str);
                    return true;
                }
                //else if (result.StatusCode == HttpStatusCode.BadRequest)
                //{
                //    var str = await result.Content.ReadAsStringAsync();
                //    Logger.Log(LoggerLevels.Debug, str);
                //}
                else
                {
                    var str = "接口调用失败：\n\tStatusCode：" + result.StatusCode + "\n\tResponse：" + result.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(str);
                    Logger.Log(LoggerLevels.Debug, str);
                }
                return false;
            }
        }
    }
}
